package com.example.study.utils;

import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.reactive.result.view.freemarker.FreeMarkerConfigurer;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Component
public class MailUtil {

    @Resource
    private JavaMailSender mailSender;

    @Resource
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送一般的文本邮件
     * @param receives 接收邮件的邮箱
     * @param subject 邮件主题
     * @param content 邮件内容
     * */
    public void sendSimpleMail(List<String> receives, String subject, String content){
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(from);
        mailMessage.setTo(receives.toArray(new String[0]));
        mailMessage.setSubject(subject);
        mailMessage.setText(content);

        mailSender.send(mailMessage);
    }

    /**
     * 发送html格式邮件
     * @param receives 接收邮件的邮箱
     * @param subject 邮件主题
     * @param content 邮件内容
     * */
    public void sendHtmlMail(List<String> receives, String subject, String content){
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(receives.toArray(new String[0]));
            helper.setSubject(subject);
            //第二个参数true表示是html格式
            helper.setText(content, true);

            mailSender.send(message);
        }catch (MessagingException e){
            e.printStackTrace();
        }
    }

    /**
     * 发送html格式邮件
     * @param receives 接收邮件的邮箱
     * @param subject 邮件主题
     * @param template 邮件模板
     * @param maps 邮件模板中占位字符对应的值
     * */
    public void sendTemplateMail(List<String> receives, String subject, String template, Map<String, Object> maps) {
       try {
           Template template1 = freeMarkerConfigurer.getConfiguration().getTemplate(template);
           //根据传值，替换模板中的占位符
           String templateHtml = FreeMarkerTemplateUtils.processTemplateIntoString(template1, maps);
           //实际的邮件发送也是一个html的邮件
           this.sendHtmlMail(receives, subject, templateHtml);
       }catch (TemplateException e){
            e.printStackTrace();
       }catch (IOException e){
           e.printStackTrace();
       }
    }

}